package com.assets.util;

import android.os.Handler;
import android.os.HandlerThread;
import android.text.TextUtils;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import com.assets.newNHF.util.LogUtils;
import com.gg.reader.api.dal.GClient;
import com.gg.reader.api.protocol.gx.EnumG;
import com.gg.reader.api.protocol.gx.MsgBaseInventoryEpc;
import com.gg.reader.api.protocol.gx.MsgBaseSetBaseband;
import com.gg.reader.api.protocol.gx.MsgBaseStop;
import com.gg.reader.api.protocol.gx.ParamEpcReadTid;

/**
 * @作者(author): WR
 * @创建时间(date): 2021/12/31
 */
public class RFIDClientUtil implements LifecycleObserver {
    private GClient client;
    private boolean isRead = false, isOpen = false;
    private RequestSuccess requestRead, requestStop;
    private HandlerThread handlerThreadMedia = new HandlerThread("word");
    private Handler mHandlerMedia;

    public void setRequestRead(RequestSuccess requestRead) {
        this.requestRead = requestRead;
    }

    public void setRequestStop(RequestSuccess requestStop) {
        this.requestStop = requestStop;
    }

    public RFIDClientUtil(RequestResult<String> result) {
        client = new GClient();
        handlerThreadMedia.start();
        mHandlerMedia = new Handler(handlerThreadMedia.getLooper());
        isOpen = client.openCusAndroidSerial("/dev/ttysWK0:115200", 64, 100);
        if (isOpen) {
            // 订阅标签上报事件
            client.onTagEpcLog = (readName, logBaseEpcInfo) -> {
              // 回调内部如有阻塞，会影响 API 正常使用
              // 标签回调数量较多，请将标签数据先缓存起来再作业务处理
                if (!isRead) return;
                if (null != logBaseEpcInfo && 0 == logBaseEpcInfo.getResult()) {
                    String epc = logBaseEpcInfo.getEpc();
                    if (TextUtils.isEmpty(epc)) return;
                    result.result(epc);
                    mHandlerMedia.removeCallbacks(runPlayMedia);
                    mHandlerMedia.postDelayed(runPlayMedia, 100);
                }
            };
// 取消订阅标签上报事件
            client.onTagEpcOver = (s, logBaseEpcOver) -> LogUtils.d("Epc log over.");
        }
    }

    public synchronized void read() {
        if (!isOpen) return;
        if (isRead) {
            return;
        }
// 1 个天线读卡, 读取 EPC 数据区以及 TID 数据区
        MsgBaseInventoryEpc msgBaseInventoryEpc = new MsgBaseInventoryEpc();
        msgBaseInventoryEpc.setAntennaEnable(EnumG.AntennaNo_1);
        msgBaseInventoryEpc.setInventoryMode(EnumG.InventoryMode_Inventory);//无限轮询
        //msgBaseInventoryEpc.setInventoryMode(0);//只读取一遍
        ParamEpcReadTid tid = new ParamEpcReadTid();
        tid.setMode(EnumG.ParamTidMode_Auto);
        tid.setLen(6);
        msgBaseInventoryEpc.setReadTid(tid);
        client.sendSynMsg(msgBaseInventoryEpc);
        if (0 == msgBaseInventoryEpc.getRtCode()) {
            isRead = true;
            if (requestRead != null) {
                requestRead.success();
            }
            LogUtils.d("Inventory epc successful.");
        } else {
            LogUtils.d("Inventory epc error.");
        }
    }

    public void stop() {
        if (!isOpen) return;
        // 停止指令，空闲态
        if (isRead) {
            MsgBaseStop msgBaseStop = new MsgBaseStop();
            client.sendSynMsg(msgBaseStop);
            if (0 == msgBaseStop.getRtCode()) {
                isRead = false;
                if (requestStop != null) {
                    requestStop.success();
                }
                LogUtils.d("Stop successful.");
            } else {
                LogUtils.d("Stop error.");
            }
        }
    }

    private void setBaseBand() {
        MsgBaseSetBaseband msgBaseSetBaseband = new MsgBaseSetBaseband();
        msgBaseSetBaseband.setqValue(0);
        msgBaseSetBaseband.setSession(1);
        client.sendSynMsg(msgBaseSetBaseband);
    }

    private Runnable runPlayMedia = new Runnable() {
        @Override
        public void run() {
            MediaUtil.getInstance().play();
            mHandlerMedia.removeCallbacks(this);
        }
    };

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop() {
        stop();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        stop();
        client.close();
        mHandlerMedia.removeCallbacksAndMessages(null);
        handlerThreadMedia.quit();
    }

}
